package com.gm.baseplatform.base.module;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public class ModuleDao extends HibernateDaoSupport {

	public void saveModule(Module module) {
		getHibernateTemplate().save(module);
	}
	
	public List<?> loadFirstLevelModule() {
		List<?> modules = getHibernateTemplate().find("from Module where parent = '" 
				+ Module.NON_PARENT + "' order by position");
		return modules;
	}
	
	public List<?> loadChildModule(final String parent) {
		return getHibernateTemplate().find("from Module where parent = '"+
				parent+"' order by position");
		
	}
	public List<?> loadChildModule(final String parent,final int firstResult,final int maxResult) {
		return (List<?>)getHibernateTemplate().execute(new HibernateCallback<Object>(){
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				String sql = "from Module where parent = ? order by position";
				return  session.createQuery(sql)
				               .setString(0,parent)
				               .setFirstResult(firstResult)
				               .setMaxResults(maxResult)
				               .list();
			}
		});
	}
	
	public Integer getChildCount(final String parent) {
		return (Integer)getHibernateTemplate().execute(new HibernateCallback<Object>(){
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				String sql = "select count(*) from Module where parent = ?";
				Query query = session.createQuery(sql).setString(0,parent);
				return ((Number)query.uniqueResult()).intValue();
			}
			
		});
	}
	
	public Module findModuleByUnid(String unid) {
		return getHibernateTemplate().get(Module.class, unid);
	}

	
}
